Popular Searches
Popular Course Categories
Popular Courses

UNIQUE and Composite Keys

UNIQUE and Composite Keys

Keys, Constraints, and Data Integrity

Understanding UNIQUE and Composite Keys in MySQL – Detailed Notes

Course: MySQL Training

Topic: Understanding UNIQUE and Composite Keys

Official Website: JustAcademy – Official Website

Course Link: MySQL Training Course

Demo Link: Register for a Course Demo


1. Introduction to UNIQUE and Composite Keys

Keys and constraints are important parts of relational database design. They help maintain data accuracy, prevent unwanted duplicate records, and establish reliable relationships between tables. MySQL provides several ways to enforce uniqueness, including the UNIQUE constraint, UNIQUE indexes, primary keys, and composite keys.

A UNIQUE constraint ensures that duplicate combinations of values are not stored in the indexed column or columns. For example, a company may require each employee to have a different employee email address.

A composite key uses two or more columns together to identify a record or enforce a uniqueness rule. For example, in a course enrollment table, a student ID and a course ID can be combined to ensure that the same student-course combination is not entered twice.

In MySQL, composite keys can be implemented as composite primary keys or composite UNIQUE constraints. The correct choice depends on whether the combination is the table's main identifier or simply another rule that must remain unique.

Example Scenario

student_id course_id email Purpose
101 201 [email protected] Student enrolled in MySQL.
101 202 [email protected] Same student enrolled in another course.
102 201 [email protected] Another student enrolled in MySQL.

In this example, an email UNIQUE constraint can prevent the same non-NULL email value from being assigned to different records. A composite UNIQUE constraint on student_id and course_id can prevent duplicate enrollment combinations while still allowing one student to take several different courses.

2. Learning Objectives

After completing this topic, you should be able to:

  • Understand the meaning and purpose of a UNIQUE constraint in MySQL.
  • Differentiate UNIQUE constraints, UNIQUE indexes, primary keys, and composite keys.
  • Create UNIQUE constraints when creating a table.
  • Add UNIQUE constraints to existing tables.
  • Understand single-column and composite UNIQUE constraints.
  • Work with composite primary keys.
  • Identify duplicate data before adding a uniqueness constraint.
  • Understand how NULL values behave in UNIQUE columns.
  • Inspect, modify, and remove UNIQUE indexes.
  • Apply uniqueness rules in practical database projects.

3. What Is a UNIQUE Constraint?

A UNIQUE constraint ensures that the indexed value or combination of values does not duplicate another indexed value or combination. It is commonly used for columns such as email addresses, usernames, product codes, and registration numbers when the business rules require uniqueness.

3.1 Simple Definition

A UNIQUE constraint prevents duplicate non-NULL key values in a column or combination of columns.

3.2 Example

CREATE TABLE Users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE,
    email VARCHAR(150) UNIQUE
);

In this table:

  • user_id is the primary key.
  • username has a UNIQUE constraint.
  • email has a UNIQUE constraint.
  • Multiple UNIQUE constraints can exist in the same table.

Two users cannot have the same non-NULL username or the same non-NULL email value. However, because the username and email columns are nullable in this example, MySQL's UNIQUE indexes generally permit multiple NULL values in either column.

3.3 Why Is UNIQUE Important?

  • Prevents duplicate values in fields that should be unique.
  • Maintains data integrity.
  • Helps enforce business rules directly in the database.
  • Supports reliable data retrieval and matching.
  • Creates a unique index that can help MySQL execute suitable queries efficiently.
  • Reduces dependence on application code alone to prevent duplicate entries.

4. Characteristics of UNIQUE Constraints

Characteristic Explanation
Uniqueness Duplicate non-NULL indexed values or combinations are rejected.
Multiple constraints A table can have multiple UNIQUE constraints.
NULL handling MySQL generally permits multiple NULL values in a UNIQUE index when the indexed column allows NULL.
Single-column support A UNIQUE constraint can apply to one column.
Composite support A UNIQUE constraint can apply to multiple columns together.
Index creation A UNIQUE constraint is enforced using a unique index.
Data validation Existing duplicate data must be addressed before a UNIQUE constraint can be added successfully.

4.1 UNIQUE Does Not Automatically Mean NOT NULL

A UNIQUE constraint and a NOT NULL constraint perform different tasks. UNIQUE prevents duplicate indexed values, while NOT NULL prevents a column from containing NULL. If a value must always be supplied and must also be unique, use both rules.

CREATE TABLE Members (
    member_id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(150) NOT NULL UNIQUE
);

Here, every member must provide an email value, and duplicate email values are rejected.

5. What Is a Composite Key?

A composite key is a key formed from two or more columns. The combination of those columns is used to enforce uniqueness or identify a row.

The term composite key describes a multi-column key. It can be a composite primary key or a composite UNIQUE key, depending on how the table is designed.

5.1 Example

Consider a table that stores which students are enrolled in which courses. A student may enroll in multiple courses, and each course may contain multiple students. The pair of student_id and course_id can identify each enrollment.

CREATE TABLE Enrollments (
    student_id INT NOT NULL,
    course_id INT NOT NULL,
    enrollment_date DATE NOT NULL,
    PRIMARY KEY (student_id, course_id)
);

Here, the combination of student_id and course_id must be unique. Neither column needs to be unique by itself.

5.2 Example Records

student_id course_id Allowed? Explanation
101 201 Yes First student-course combination.
101 202 Yes Same student, different course.
102 201 Yes Different student, same course.
101 201 No The combination already exists.

6. Difference Between a Composite Primary Key and a Composite UNIQUE Key

Both types use multiple columns, but their purpose differs.

Feature Composite Primary Key Composite UNIQUE Key
Purpose Provides the table's main multi-column identifier. Enforces uniqueness for a multi-column combination.
Number per table Only one primary key constraint. Multiple UNIQUE constraints are allowed.
NULL values All primary key columns are NOT NULL. Nullable columns can allow NULL values; MySQL generally permits multiple entries where at least one indexed component is NULL.
Typical example (student_id, course_id) identifies an enrollment row. (country_code, phone_number) must not repeat as a non-NULL combination.
Other identifiers Other unique constraints may also exist. A separate primary key may identify each row.

6.1 Composite Primary Key Example

CREATE TABLE OrderItems (
    order_id INT NOT NULL,
    product_id INT NOT NULL,
    quantity INT NOT NULL DEFAULT 1,
    PRIMARY KEY (order_id, product_id)
);

The same product can appear in different orders, and each order can contain different products. However, the same product cannot appear twice as separate rows for the same order under this key design.

6.2 Composite UNIQUE Key Example

CREATE TABLE CourseSchedules (
    schedule_id INT AUTO_INCREMENT PRIMARY KEY,
    course_id INT NOT NULL,
    classroom_id INT NOT NULL,
    class_date DATE NOT NULL,
    UNIQUE (classroom_id, class_date)
);

This design prevents the same classroom from being assigned to two schedule records on the same date. It still allows each schedule to have its own single-column primary key.

7. Creating a UNIQUE Constraint During Table Creation

You can define a UNIQUE constraint directly in a CREATE TABLE statement. For a single column, the constraint can be declared beside the column. For a composite UNIQUE key, define the constraint at table level.

7.1 Single-Column UNIQUE Constraint

CREATE TABLE Employees (
    employee_id INT AUTO_INCREMENT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    work_email VARCHAR(150) NOT NULL UNIQUE,
    phone_number VARCHAR(20)
);

The work_email column must contain a unique, non-NULL value for every employee.

7.2 Named UNIQUE Constraint

CREATE TABLE Customers (
    customer_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL,
    CONSTRAINT uq_customers_email UNIQUE (email)
);

The constraint is named uq_customers_email. Giving constraints meaningful names can make database maintenance and troubleshooting easier.

7.3 Composite UNIQUE Constraint

CREATE TABLE RoomBookings (
    booking_id INT AUTO_INCREMENT PRIMARY KEY,
    room_id INT NOT NULL,
    booking_date DATE NOT NULL,
    customer_name VARCHAR(100) NOT NULL,
    CONSTRAINT uq_room_date UNIQUE (room_id, booking_date)
);

This example allows a room to be booked on different dates and allows different rooms to be booked on the same date. It prevents duplicate room-and-date combinations.

8. Inserting Data into Tables with UNIQUE Constraints

When inserting data, MySQL checks whether the new value or combination violates any UNIQUE constraint. If it does, the statement normally fails with a duplicate-key error.

8.1 Insert Valid Records

CREATE TABLE AppUsers (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(150) NOT NULL UNIQUE
);

INSERT INTO AppUsers (username, email)
VALUES
('rahul101', '[email protected]'),
('priya102', '[email protected]'),
('amit103', '[email protected]');

These records are valid because the usernames and email addresses are distinct.

8.2 Attempt to Insert a Duplicate Username

INSERT INTO AppUsers (username, email)
VALUES ('rahul101', '[email protected]');

This statement fails because rahul101 already exists in the username column.

8.3 Attempt to Insert a Duplicate Email

INSERT INTO AppUsers (username, email)
VALUES ('newuser104', '[email protected]');

This statement fails because the email address already exists.

8.4 Check Existing Records

SELECT *
FROM AppUsers
WHERE username = 'rahul101';

SELECT *
FROM AppUsers
WHERE email = '[email protected]';

Use these queries to identify the record that conflicts with a proposed insert.

9. Understanding NULL Values in UNIQUE Constraints

In MySQL, a UNIQUE index generally allows multiple NULL values in a column that permits NULL. This is because NULL represents a missing or unknown value and is not treated like an ordinary value for unique-index comparisons.

9.1 Example

CREATE TABLE Contacts (
    contact_id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(150) UNIQUE
);

INSERT INTO Contacts (email)
VALUES
(NULL),
(NULL),
('[email protected]');

In MySQL, these inserts are generally allowed because the email column permits NULL and the non-NULL email value is unique.

9.2 Enforcing a Required Unique Value

CREATE TABLE RequiredContacts (
    contact_id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(150) NOT NULL UNIQUE
);

With this design, each record must contain an email value, and no two records may have the same email.

9.3 NULL Values in Composite UNIQUE Keys

When one or more columns in a composite UNIQUE index are nullable, MySQL generally permits rows where at least one indexed component is NULL, even when the other indexed values match. If the business rule requires every component of the combination, declare those columns NOT NULL.

CREATE TABLE OptionalAssignments (
    employee_id INT NOT NULL,
    project_id INT NULL,
    UNIQUE (employee_id, project_id)
);

For predictable enforcement of a complete employee-project combination, use NOT NULL on both columns if the application requires every assignment to have an employee and a project.

10. Adding a UNIQUE Constraint to an Existing Table

If a table already exists, you can add a UNIQUE constraint using ALTER TABLE. The operation succeeds only if existing records satisfy the uniqueness rule and the index can be created.

10.1 Example Table

CREATE TABLE Staff (
    staff_id INT AUTO_INCREMENT PRIMARY KEY,
    staff_name VARCHAR(100) NOT NULL,
    work_email VARCHAR(150)
);

10.2 Add a UNIQUE Constraint

ALTER TABLE Staff
ADD CONSTRAINT uq_staff_work_email UNIQUE (work_email);

This adds a named UNIQUE constraint to the work email column. Since the column is nullable, multiple NULL values may be allowed.

10.3 Add a Composite UNIQUE Constraint

ALTER TABLE Staff
ADD CONSTRAINT uq_staff_name_email
UNIQUE (staff_name, work_email);

This enforces uniqueness on the combination of staff name and work email. It does not require staff names or email values to be unique individually.

Important: Adding the second constraint above is appropriate only if that combination is a genuine business rule. If the email address itself must be unique, use a separate UNIQUE constraint on the email column instead.

11. Creating a UNIQUE Index with CREATE UNIQUE INDEX

MySQL supports the CREATE UNIQUE INDEX statement to create a unique index on one or more columns. It provides another way to enforce uniqueness.

11.1 Single-Column UNIQUE Index

CREATE UNIQUE INDEX uq_staff_email
ON Staff (work_email);

This creates a unique index on work_email. Do not run this if an equivalent UNIQUE index already exists, as doing so may create a duplicate index error or unnecessary duplicate indexing.

11.2 Composite UNIQUE Index

CREATE UNIQUE INDEX uq_employee_project
ON EmployeeProjects (employee_id, project_id);

This index prevents duplicate combinations of employee ID and project ID.

11.3 UNIQUE Constraint vs. UNIQUE Index

For ordinary table design, a UNIQUE constraint and a UNIQUE index both enforce uniqueness in MySQL. The choice often comes down to clarity and how the schema is managed. Use a constraint declaration when expressing a business rule in a table definition, and use CREATE UNIQUE INDEX when managing indexes explicitly.

12. Understanding Composite Key Column Order

The order of columns in a composite key matters for index access patterns. For uniqueness enforcement, a composite UNIQUE index on (column_a, column_b) requires the pair to be unique; it does not independently make either column unique.

12.1 Example

CREATE TABLE EmployeeProjects (
    employee_id INT NOT NULL,
    project_id INT NOT NULL,
    assigned_date DATE NOT NULL,
    PRIMARY KEY (employee_id, project_id)
);

With this primary key, the following combinations are valid:

employee_id project_id Result
10 501 Allowed
10 502 Allowed
11 501 Allowed
10 501 Rejected as a duplicate

12.2 Why Column Order Matters for Queries

A composite index on (employee_id, project_id) is generally well suited to queries filtering by employee ID, or by both employee ID and project ID. It is not usually as directly useful for queries filtering only by project ID, because project ID is not the leading column.

-- Uses the leading column of the composite key.
SELECT *
FROM EmployeeProjects
WHERE employee_id = 10;

-- Filters by both key columns.
SELECT *
FROM EmployeeProjects
WHERE employee_id = 10
  AND project_id = 501;

-- May benefit from a separate index beginning with project_id.
SELECT *
FROM EmployeeProjects
WHERE project_id = 501;

Use EXPLAIN and real query workloads to decide whether additional indexes are necessary. Do not add indexes without considering storage and write overhead.

13. Difference Between UNIQUE, PRIMARY KEY, and Composite Keys

Feature PRIMARY KEY UNIQUE Composite Key
Meaning Main identifier for rows. Enforces uniqueness. A key composed of multiple columns.
Column count One or more columns. One or more columns. Two or more columns by definition.
Number per table One primary key constraint. Multiple UNIQUE constraints allowed. Can be primary or UNIQUE; multiple composite UNIQUE constraints may exist.
NULL behavior Key columns cannot be NULL. Nullable columns can permit multiple NULL values. Depends on whether it is a primary key or UNIQUE constraint and on column nullability.
Example student_id email (student_id, course_id)
Typical use Identifying one row. Preventing duplicate business values. Enforcing uniqueness of a combination.

14. Modifying and Removing UNIQUE Constraints

When business rules change, you may need to remove or replace a UNIQUE constraint. In MySQL, UNIQUE constraints are implemented by indexes, so you normally remove the corresponding index with ALTER TABLE ... DROP INDEX.

14.1 Find Existing Indexes

SHOW INDEX FROM Staff;

Inspect the index names and indexed columns before attempting to remove an index.

14.2 Remove a UNIQUE Index

ALTER TABLE Staff
DROP INDEX uq_staff_work_email;

This removes the index named uq_staff_work_email. Replace the name with the actual index name from your table definition.

14.3 Check the Table Definition

SHOW CREATE TABLE Staff;

This displays the table definition and helps you confirm which constraints and indexes are present.

14.4 Important Considerations

  • Check whether application code relies on the uniqueness rule.
  • Inspect foreign key dependencies if the index is involved in a relationship.
  • Do not drop an index used to support a required foreign key relationship without planning a replacement.
  • Validate existing records before recreating a UNIQUE index.
  • Test schema changes in a development or staging environment before production deployment.

15. Finding Duplicate Records Before Adding UNIQUE

Before adding a UNIQUE constraint to existing data, check whether the selected values or combinations contain duplicates. This is especially important for older tables that were created without proper constraints.

15.1 Find Duplicate Email Addresses

SELECT
    email,
    COUNT(*) AS total
FROM Customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;

This query returns non-NULL email values that occur more than once. For case-sensitive or case-insensitive text comparisons, results depend on the column's collation.

15.2 Find Duplicate Composite Combinations

SELECT
    student_id,
    course_id,
    COUNT(*) AS total
FROM Enrollments
GROUP BY student_id, course_id
HAVING COUNT(*) > 1;

This query identifies duplicate student-course combinations that would prevent the corresponding composite UNIQUE constraint or composite primary key from being added.

15.3 Find NULL Values

SELECT *
FROM Customers
WHERE email IS NULL;

NULL values do not generally violate a UNIQUE constraint in MySQL. However, if the business rule requires every customer to have an email address, you must also enforce NOT NULL and resolve missing data appropriately.

15.4 Resolve Duplicate Data Carefully

  1. Run duplicate-detection queries.
  2. Review the affected rows and determine whether they are genuinely duplicates or valid separate records.
  3. Correct, merge, or remove records according to the application's business rules.
  4. Back up important data before performing destructive changes.
  5. Recheck duplicates and NULL values as appropriate.
  6. Add the UNIQUE constraint after the data satisfies the intended rule.

16. Practical Project: User Registration System

This project demonstrates how primary keys and UNIQUE constraints work together in a user registration database.

Step 1: Create the Database

CREATE DATABASE RegistrationDB;
USE RegistrationDB;

Step 2: Create the Users Table

CREATE TABLE Users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(150) NOT NULL,
    phone_number VARCHAR(20),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT uq_users_username UNIQUE (username),
    CONSTRAINT uq_users_email UNIQUE (email)
);

Step 3: Insert Valid Records

INSERT INTO Users (username, email, phone_number)
VALUES
('rahul101', '[email protected]', '9000000001'),
('priya102', '[email protected]', '9000000002'),
('amit103', '[email protected]', '9000000003');

Step 4: Retrieve Users

SELECT *
FROM Users
ORDER BY user_id;

Step 5: Test Username Uniqueness

INSERT INTO Users (username, email, phone_number)
VALUES ('rahul101', '[email protected]', '9000000004');

The insert is rejected because the username already exists.

Step 6: Test Email Uniqueness

INSERT INTO Users (username, email, phone_number)
VALUES ('newuser104', '[email protected]', '9000000005');

The insert is rejected because the email already exists.

Step 7: Inspect the Constraints

SHOW CREATE TABLE Users;
SHOW INDEX FROM Users;

These commands help verify the primary key and the UNIQUE indexes on username and email.

17. Practical Project: Course Enrollment with a Composite UNIQUE Key

In this project, a student can enroll in multiple courses, but the same student should not be enrolled in the same course twice.

Step 1: Create the Table

CREATE TABLE CourseEnrollments (
    enrollment_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT NOT NULL,
    course_id INT NOT NULL,
    enrollment_date DATE NOT NULL,
    status VARCHAR(30) NOT NULL DEFAULT 'Active',
    CONSTRAINT uq_student_course UNIQUE (student_id, course_id)
);

This design uses a separate primary key for each enrollment and a composite UNIQUE constraint to enforce the student-course business rule.

Step 2: Insert Valid Records

INSERT INTO CourseEnrollments
(student_id, course_id, enrollment_date)
VALUES
(101, 201, '2026-02-01'),
(101, 202, '2026-02-02'),
(102, 201, '2026-02-03');

Step 3: Attempt a Duplicate Enrollment

INSERT INTO CourseEnrollments
(student_id, course_id, enrollment_date)
VALUES
(101, 201, '2026-02-10');

The insert is rejected because the pair (101, 201) already exists. The new enrollment date does not make the student-course combination unique.

Step 4: Retrieve a Student's Courses

SELECT *
FROM CourseEnrollments
WHERE student_id = 101;

Step 5: Check for Duplicate Combinations

SELECT
    student_id,
    course_id,
    COUNT(*) AS total
FROM CourseEnrollments
GROUP BY student_id, course_id
HAVING COUNT(*) > 1;

The query should return no rows when the uniqueness rule is satisfied.

18. Common Errors and Troubleshooting

Problem Cause Solution
Duplicate entry error The value or indexed combination already exists. Inspect existing records and choose a valid new value or correct the intended record operation.
Cannot add UNIQUE index Existing rows contain duplicate combinations. Run GROUP BY and HAVING queries to identify conflicts.
Multiple NULL values appear The UNIQUE column permits NULL. Add NOT NULL if the business rule requires a value for every row.
Individual columns repeat in a composite key Only the combination is required to be unique. Check the full combination, not each column separately.
Unexpected duplicate comparison results Column collation or data normalization affects string comparisons. Review collation, whitespace, case handling, and the business definition of equality.
Cannot drop an index The index may be needed by a constraint or foreign key. Inspect dependencies and plan an appropriate replacement before removal.
Duplicate index created unnecessarily An equivalent UNIQUE index already exists. Inspect SHOW INDEX and avoid redundant indexes.

18.1 Error: Duplicate Entry

Suppose the username rahul101 already exists. An insert using the same username will fail.

SELECT *
FROM Users
WHERE username = 'rahul101';

Review the existing user and decide whether the intended action is to create a new user or update the existing one. Do not change a unique identifier merely to hide an error if it would violate the business rules.

18.2 Error: Cannot Add a UNIQUE Constraint

Run a duplicate check on the intended key columns before adding the constraint.

SELECT email, COUNT(*) AS total
FROM Customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;

After investigating and correcting the data, try adding the constraint again.

18.3 Case Sensitivity and Whitespace

Whether two strings such as Admin and admin are treated as equal depends on the column's collation. Trailing spaces and string type behavior can also affect comparisons. Review the column definition and collation when a UNIQUE constraint produces unexpected results.

19. Best Practices for UNIQUE and Composite Keys

  1. Enforce business rules in the database: Do not rely exclusively on application code to prevent duplicate values.
  2. Use NOT NULL when values are required: UNIQUE alone does not guarantee that a value is present.
  3. Choose composite keys carefully: Include only the columns needed to represent the intended uniqueness rule.
  4. Use meaningful names: Names such as uq_users_email and uq_student_course make constraints easier to identify.
  5. Check existing data first: Find duplicate combinations before adding a UNIQUE constraint to an existing table.
  6. Understand NULL behavior: A UNIQUE constraint generally allows multiple NULL values in nullable indexed columns.
  7. Review collation and normalization: Define how values such as email addresses and usernames should be compared.
  8. Avoid redundant indexes: Multiple indexes on the same columns can increase storage use and write overhead.
  9. Use EXPLAIN for important queries: Confirm whether an index is useful for actual query patterns.
  10. Test changes safely: Test index additions and removals before deploying them to production.
  11. Back up important data: Keep a recovery plan before making structural changes or cleaning duplicate records.

20. Practice Exercises

Exercise 1: Create a Users Table

Create a table with the following columns:

  • user_id – AUTO_INCREMENT primary key.
  • username – required and unique.
  • email – required and unique.
  • full_name – required.

Expected solution:

CREATE TABLE PracticeUsers (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(150) NOT NULL UNIQUE,
    full_name VARCHAR(100) NOT NULL
);

Exercise 2: Test Duplicate Values

Insert two users with different usernames and emails. Then attempt to reuse the first username with a different email. Observe the duplicate-key error and explain why it occurs.

Exercise 3: Create a Composite UNIQUE Key

Create a table called StudentCourses with a primary key named enrollment_id, plus student_id and course_id. Add a composite UNIQUE constraint on student ID and course ID.

CREATE TABLE StudentCourses (
    enrollment_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT NOT NULL,
    course_id INT NOT NULL,
    CONSTRAINT uq_student_course
        UNIQUE (student_id, course_id)
);

Exercise 4: Find Duplicate Combinations

Write a query to identify duplicate student-course combinations using GROUP BY and HAVING COUNT(*) > 1.

Exercise 5: Compare Composite Key Designs

Create one table using PRIMARY KEY (student_id, course_id) and another using an independent primary key with UNIQUE (student_id, course_id). Explain when each design might be appropriate.

Exercise 6: Inspect and Remove a UNIQUE Index

Use SHOW INDEX to identify a UNIQUE index. Remove it in a practice database using ALTER TABLE ... DROP INDEX, then verify the updated table definition.

21. Interview Questions and Answers

Q1. What is a UNIQUE constraint in MySQL?

Answer: A UNIQUE constraint prevents duplicate non-NULL values or combinations of values in its indexed columns.

Q2. Can a table have multiple UNIQUE constraints?

Answer: Yes. A table can have multiple UNIQUE constraints, such as one on username and another on email.

Q3. Does UNIQUE allow NULL values in MySQL?

Answer: Yes. MySQL generally allows multiple NULL values in a UNIQUE index if the indexed columns permit NULL.

Q4. What is a composite key?

Answer: A composite key is formed from two or more columns that work together to enforce uniqueness or identify a record.

Q5. What is the difference between a composite primary key and a composite UNIQUE key?

Answer: A composite primary key is the table's main identifier and its columns cannot be NULL. A composite UNIQUE key enforces uniqueness on a column combination but can allow NULL values if its columns are nullable.

Q6. Can individual columns repeat in a composite UNIQUE key?

Answer: Yes. The individual columns can repeat as long as the complete non-NULL combination does not violate the UNIQUE constraint.

Q7. How do you create a UNIQUE constraint?

Answer: Define UNIQUE (column_name) or UNIQUE (column1, column2) in a CREATE TABLE statement, or add the constraint using ALTER TABLE.

Q8. How do you create a UNIQUE index?

Answer: Use CREATE UNIQUE INDEX index_name ON table_name (column_name).

Q9. How do you find duplicate values before adding a UNIQUE constraint?

Answer: Use GROUP BY on the intended key columns and filter groups with HAVING COUNT(*) > 1.

Q10. How can you remove a UNIQUE index?

Answer: Use ALTER TABLE table_name DROP INDEX index_name, after checking dependencies and confirming the index name.

Q11. Does a UNIQUE constraint automatically create a primary key?

Answer: No. A UNIQUE constraint is not the same as a primary key. MySQL can have multiple UNIQUE constraints, while each table has only one primary key constraint.

Q12. Why is a composite UNIQUE key useful in an enrollment table?

Answer: It can prevent a student from being enrolled in the same course more than once while allowing the student to enroll in different courses.

22. Quick Revision Checklist

  • UNIQUE prevents duplicate indexed values or combinations.
  • A table can have multiple UNIQUE constraints.
  • UNIQUE does not automatically mean NOT NULL.
  • MySQL generally permits multiple NULL values in nullable UNIQUE indexes.
  • A composite key uses two or more columns together.
  • A composite key can be a primary key or a UNIQUE key.
  • A composite UNIQUE key does not require each individual column to be unique.
  • Use ALTER TABLE to add or remove UNIQUE indexes.
  • Use CREATE UNIQUE INDEX to create a unique index explicitly.
  • Use GROUP BY and HAVING to identify duplicate combinations.
  • Review collation, NULL handling, and index column order when designing keys.
  • Test schema changes before applying them to production.

23. Conclusion

UNIQUE constraints and composite keys are essential tools for maintaining reliable data in MySQL. A UNIQUE constraint prevents duplicate values in a single column or a combination of columns, while a composite key combines multiple columns to enforce a uniqueness rule or identify a record.

Use a single-column UNIQUE constraint for values such as usernames and email addresses when they must not repeat. Use a composite UNIQUE key when a particular combination, such as student ID and course ID, must be unique. Choose a composite primary key when that combination is the table's main identifier, and choose a separate primary key with a composite UNIQUE constraint when the table needs an independent row identifier as well.

Always validate existing data before adding uniqueness constraints, understand MySQL's NULL behavior, and select indexes based on actual data rules and query patterns. Applying these practices will help you build accurate, consistent, and maintainable MySQL databases.


Learn More with JustAcademy

Visit the JustAcademy official website to explore training resources and courses.

Learn more about database design and SQL through the MySQL Training Course.

You can also register for a course demo to explore the training program.

whatsapp